"""
主机管理相关的异步任务
"""
import socket
import paramiko
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from django.utils import timezone
from .models import Host
import logging

logger = logging.getLogger(__name__)


def is_private_ip(ip):
    """检查是否是内网IP地址"""
    if not ip:
        return False

    try:
        parts = ip.split('.')
        if len(parts) != 4:
            return False

        # 转换为整数
        octets = [int(part) for part in parts]

        # 检查是否是内网IP段
        # 10.0.0.0/8
        if octets[0] == 10:
            return True
        # 172.16.0.0/12
        elif octets[0] == 172 and 16 <= octets[1] <= 31:
            return True
        # 192.168.0.0/16
        elif octets[0] == 192 and octets[1] == 168:
            return True

        return False
    except (ValueError, IndexError):
        return False


class OptimizedHostManager:
    """优化的主机管理器 - 合并连通性检测和信息获取"""

    def __init__(self):
        self.running = False
        self.check_interval = 10  # 检测间隔10秒，减少频率提升性能
        self.thread = None
        self.max_workers = 8  # 最大线程数

    def start(self):
        """启动主机监控"""
        if not self.running:
            self.running = True
            self.thread = threading.Thread(target=self._monitor_loop, daemon=True)
            self.thread.start()
            # logger.info("优化的主机监控已启动")  # 注释掉避免终端输出干扰

    def stop(self):
        """停止主机监控"""
        self.running = False
        if self.thread:
            self.thread.join()
        # logger.info("优化的主机监控已停止")  # 注释掉避免终端输出干扰

    def _monitor_loop(self):
        """监控循环"""
        while self.running:
            try:
                self.check_all_hosts_parallel()
            except Exception as e:
                logger.error(f"主机监控出错: {e}")

            # 等待下次检测
            time.sleep(self.check_interval)

    def check_all_hosts_parallel(self):
        """并行检测所有主机的连通性和信息"""
        hosts = list(Host.objects.all())
        if not hosts:
            return

        # logger.info(f"开始并行检测 {len(hosts)} 台主机")  # 注释掉避免终端输出干扰

        # 使用线程池并行处理
        with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
            # 提交所有任务
            future_to_host = {
                executor.submit(self._check_and_update_host, host): host
                for host in hosts
            }

            # 收集结果
            completed_count = 0
            for future in as_completed(future_to_host):
                host = future_to_host[future]
                try:
                    result = future.result(timeout=30)  # 30秒超时
                    completed_count += 1
                    if result.get('status_changed'):
                        # logger.info(f"主机 {host.hostname} 状态变更: {result['old_status']} -> {result['new_status']}")  # 注释掉避免终端输出干扰
                        pass
                except Exception as e:
                    logger.error(f"检测主机 {host.hostname} 失败: {e}")
                    # 出错时设置为离线
                    self._set_host_offline(host)

            # logger.info(f"并行检测完成，处理了 {completed_count}/{len(hosts)} 台主机")  # 注释掉避免终端输出干扰

    def _check_and_update_host(self, host):
        """检测并更新单个主机的连通性和信息"""
        try:
            # 1. 首先检测连通性
            is_online = self.check_host_connectivity(host)
            old_status = host.status
            new_status = 'online' if is_online else 'offline'

            # 2. 更新状态
            status_changed = False
            if old_status != new_status:
                host.status = new_status
                host.updated_at = timezone.now()
                host.save(update_fields=['status', 'updated_at'])
                status_changed = True

            # 3. 如果主机在线且状态发生变化，尝试获取系统信息
            if is_online and (status_changed or self._should_update_info(host)):
                try:
                    system_info = get_enhanced_system_info(host)
                    if system_info:
                        self._update_host_info(host, system_info)
                except Exception as e:
                    logger.debug(f"获取主机 {host.hostname} 系统信息失败: {e}")

            return {
                'success': True,
                'online': is_online,
                'status_changed': status_changed,
                'old_status': old_status,
                'new_status': new_status
            }

        except Exception as e:
            logger.error(f"检测主机 {host.hostname} 失败: {e}")
            return {
                'success': False,
                'error': str(e)
            }

    def _should_update_info(self, host):
        """判断是否需要更新主机信息"""
        # 如果主机信息不完整或者超过1小时未更新，则需要更新
        if not host.cpu or not host.memory or not host.disk:
            return True

        # 检查更新时间
        if host.updated_at:
            time_diff = timezone.now() - host.updated_at
            return time_diff.total_seconds() > 3600  # 1小时

        return True

    def _update_host_info(self, host, system_info):
        """更新主机信息"""
        updated_fields = []
        for key, value in system_info.items():
            if hasattr(host, key) and value:
                old_value = getattr(host, key)
                if old_value != value:
                    setattr(host, key, value)
                    updated_fields.append(key)

        if updated_fields:
            host.updated_at = timezone.now()
            host.save()
            # logger.debug(f"主机 {host.hostname} 更新了 {len(updated_fields)} 个字段")  # 注释掉避免终端输出干扰

    def _set_host_offline(self, host):
        """设置主机为离线状态"""
        if host.status != 'offline':
            host.status = 'offline'
            host.updated_at = timezone.now()
            host.save(update_fields=['status', 'updated_at'])

    def check_host_connectivity(self, host):
        """检测单个主机的连通性（优化版）"""
        try:
            # 首先检测端口连通性（减少超时时间）
            if not self._check_port_connectivity(host.public_ip, host.port, timeout=3):
                return False

            # 如果端口通，尝试SSH连接验证（减少超时时间）
            return self._check_ssh_connectivity(host, timeout=5)

        except Exception as e:
            logger.debug(f"主机 {host.hostname} 连通性检测失败: {e}")
            return False

    def _check_port_connectivity(self, ip, port, timeout=3):
        """检测端口连通性（优化版）"""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(timeout)
            result = sock.connect_ex((ip, port))
            sock.close()
            return result == 0
        except Exception:
            return False

    def _check_ssh_connectivity(self, host, timeout=5):
        """检测SSH连通性（优化版）"""
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            # 处理localhost特殊情况
            hostname = host.public_ip
            if hostname in ['localhost', '127.0.0.1', '::1']:
                hostname = '127.0.0.1'

            # 根据认证方式连接
            if host.auth_type == 'password':
                ssh.connect(
                    hostname=hostname,
                    port=host.port,
                    username=host.username,
                    password=host.password,
                    timeout=timeout,
                    banner_timeout=timeout,
                    allow_agent=False,
                    look_for_keys=False
                )
            elif host.auth_type == 'key':
                # 处理私钥认证
                from io import StringIO
                private_key = paramiko.RSAKey.from_private_key(
                    StringIO(host.private_key),
                    password=host.passphrase if host.passphrase else None
                )
                ssh.connect(
                    hostname=hostname,
                    port=host.port,
                    username=host.username,
                    pkey=private_key,
                    timeout=timeout,
                    banner_timeout=timeout,
                    allow_agent=False,
                    look_for_keys=False
                )

            # 执行简单命令测试（减少超时时间）
            _, stdout, _ = ssh.exec_command('echo "test"', timeout=3)
            output = stdout.read().decode().strip()
            ssh.close()

            return output == "test"

        except Exception as e:
            logger.debug(f"SSH连接测试失败 {host.hostname}: {e}")
            return False


# 全局优化主机管理器实例
optimized_host_manager = OptimizedHostManager()


def start_connectivity_monitoring():
    """启动连通性监控（使用优化版本）"""
    optimized_host_manager.start()


def stop_connectivity_monitoring():
    """停止连通性监控（使用优化版本）"""
    optimized_host_manager.stop()


def check_single_host(host_id):
    """检测单个主机连通性（使用优化版本）"""
    try:
        host = Host.objects.get(id=host_id)
        is_online = optimized_host_manager.check_host_connectivity(host)

        old_status = host.status
        new_status = 'online' if is_online else 'offline'

        if old_status != new_status:
            host.status = new_status
            host.updated_at = timezone.now()
            host.save(update_fields=['status', 'updated_at'])

        return {
            'success': True,
            'online': is_online,
            'status': new_status,
            'message': f'主机连接{"成功" if is_online else "失败"}'
        }

    except Host.DoesNotExist:
        return {
            'success': False,
            'message': '主机不存在'
        }
    except Exception as e:
        logger.error(f"检测主机连通性失败: {e}")
        return {
            'success': False,
            'message': f'检测失败: {str(e)}'
        }


def get_system_info_via_ssh(host):
    """通过SSH获取主机系统信息"""
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # 连接SSH
        # 处理localhost特殊情况
        hostname = host.public_ip
        if hostname in ['localhost', '127.0.0.1', '::1']:
            hostname = '127.0.0.1'

        if host.auth_type == 'password':
            ssh.connect(
                hostname=hostname,
                port=host.port,
                username=host.username,
                password=host.password,
                timeout=10,
                allow_agent=False,
                look_for_keys=False
            )
        elif host.auth_type == 'key':
            from io import StringIO
            private_key = paramiko.RSAKey.from_private_key(
                StringIO(host.private_key),
                password=host.passphrase if host.passphrase else None
            )
            ssh.connect(
                hostname=hostname,
                port=host.port,
                username=host.username,
                pkey=private_key,
                timeout=10,
                allow_agent=False,
                look_for_keys=False
            )

        # 获取系统信息
        system_info = {}

        # CPU信息
        _, stdout, _ = ssh.exec_command('cat /proc/cpuinfo | grep "model name" | head -1 | cut -d: -f2')
        cpu_info = stdout.read().decode().strip()
        if cpu_info:
            system_info['cpu_info'] = cpu_info

        # CPU核心数
        _, stdout, _ = ssh.exec_command('nproc')
        cpu_cores = stdout.read().decode().strip()
        if cpu_cores:
            system_info['cpu'] = f"{cpu_cores}核"

        # 内存信息
        _, stdout, _ = ssh.exec_command('free -h | grep Mem | awk \'{print $2}\'')
        memory = stdout.read().decode().strip()
        if memory:
            system_info['memory'] = memory

        # 磁盘信息
        _, stdout, _ = ssh.exec_command('df -h / | tail -1 | awk \'{print $2}\'')
        disk = stdout.read().decode().strip()
        if disk:
            system_info['disk'] = disk

        # 操作系统信息
        _, stdout, _ = ssh.exec_command('cat /etc/os-release | grep PRETTY_NAME | cut -d= -f2 | tr -d \'"\'')
        os_info = stdout.read().decode().strip()
        if os_info:
            parts = os_info.split()
            if len(parts) >= 2:
                system_info['os'] = parts[0]
                system_info['os_version'] = ' '.join(parts[1:])
            else:
                system_info['os'] = os_info

        # CPU架构
        _, stdout, _ = ssh.exec_command('uname -m')
        cpu_arch = stdout.read().decode().strip()
        if cpu_arch:
            system_info['cpu_arch'] = cpu_arch

        ssh.close()
        return system_info

    except Exception as e:
        logger.error(f"获取主机 {host.hostname} 系统信息失败: {e}")
        return {}


def auto_detect_host_info(host_id):
    """自动检测主机信息"""
    try:
        host = Host.objects.get(id=host_id)
        system_info = get_system_info_via_ssh(host)

        if system_info:
            # 更新主机信息
            for key, value in system_info.items():
                if hasattr(host, key) and value:
                    setattr(host, key, value)

            host.updated_at = timezone.now()
            host.save()

            return {
                'success': True,
                'message': '主机信息检测完成',
                'data': system_info
            }
        else:
            return {
                'success': False,
                'message': '无法获取主机信息'
            }

    except Host.DoesNotExist:
        return {
            'success': False,
            'message': '主机不存在'
        }
    except Exception as e:
        logger.error(f"自动检测主机信息失败: {e}")
        return {
            'success': False,
            'message': f'检测失败: {str(e)}'
        }


def batch_auto_detect_hosts(host_ids):
    """批量自动检测多个主机信息（并行优化版）"""
    if not host_ids:
        return {
            'success': True,
            'message': '没有主机需要检测',
            'results': []
        }

    results = []
    max_workers = min(8, len(host_ids))  # 最大8个线程

    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        # 提交所有任务
        future_to_host_id = {
            executor.submit(auto_detect_enhanced_host_info, host_id): host_id
            for host_id in host_ids
        }

        # 收集结果
        for future in as_completed(future_to_host_id):
            host_id = future_to_host_id[future]
            try:
                result = future.result(timeout=60)  # 60秒超时
                results.append({
                    'host_id': host_id,
                    'result': result
                })
            except Exception as e:
                logger.error(f"检测主机 {host_id} 失败: {e}")
                results.append({
                    'host_id': host_id,
                    'result': {
                        'success': False,
                        'message': f'检测失败: {str(e)}'
                    }
                })

    success_count = sum(1 for r in results if r['result']['success'])
    return {
        'success': True,
        'message': f'批量检测完成，共处理 {len(host_ids)} 台主机，成功 {success_count} 台',
        'results': results,
        'total': len(host_ids),
        'success_count': success_count,
        'fail_count': len(host_ids) - success_count
    }


def refresh_all_hosts():
    """刷新所有在线主机信息"""
    try:
        # 只获取在线主机
        online_hosts = Host.objects.filter(status='online')
        host_ids = [host.id for host in online_hosts]

        if not host_ids:
            return {
                'success': True,
                'message': '没有在线主机需要刷新'
            }

        # 批量检测在线主机
        result = batch_auto_detect_hosts(host_ids)

        # 统计成功和失败的数量
        success_count = sum(1 for r in result['results'] if r['result']['success'])
        fail_count = len(host_ids) - success_count

        return {
            'success': True,
            'message': f'刷新完成：成功 {success_count} 台在线主机，失败 {fail_count} 台',
            'total': len(host_ids),
            'success_count': success_count,
            'fail_count': fail_count
        }

    except Exception as e:
        logger.error(f"刷新在线主机信息失败: {e}")
        return {
            'success': False,
            'message': f'刷新失败: {str(e)}'
        }


def get_enhanced_system_info(host):
    """获取增强的系统信息"""
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # 连接SSH
        # 处理localhost特殊情况
        hostname = host.public_ip
        if hostname in ['localhost', '127.0.0.1', '::1']:
            hostname = '127.0.0.1'

        if host.auth_type == 'password':
            ssh.connect(
                hostname=hostname,
                port=host.port,
                username=host.username,
                password=host.password,
                timeout=15,
                allow_agent=False,
                look_for_keys=False
            )
        elif host.auth_type == 'key':
            from io import StringIO
            private_key = paramiko.RSAKey.from_private_key(
                StringIO(host.private_key),
                password=host.passphrase if host.passphrase else None
            )
            ssh.connect(
                hostname=hostname,
                port=host.port,
                username=host.username,
                pkey=private_key,
                timeout=15,
                allow_agent=False,
                look_for_keys=False
            )

        system_info = {}

        # 获取详细的CPU信息
        commands = {
            'cpu_model': 'cat /proc/cpuinfo | grep "model name" | head -1 | cut -d: -f2 | xargs',
            'cpu_cores': 'nproc',
            'cpu_arch': 'uname -m',
            'cpu_freq': 'cat /proc/cpuinfo | grep "cpu MHz" | head -1 | cut -d: -f2 | xargs',

            # 内存信息
            'memory_total': 'free -h | grep Mem | awk \'{print $2}\'',
            'memory_used': 'free -h | grep Mem | awk \'{print $3}\'',
            'memory_available': 'free -h | grep Mem | awk \'{print $7}\'',

            # 磁盘信息
            'disk_total': 'df -h / | tail -1 | awk \'{print $2}\'',
            'disk_used': 'df -h / | tail -1 | awk \'{print $3}\'',
            'disk_available': 'df -h / | tail -1 | awk \'{print $4}\'',
            'disk_usage': 'df -h / | tail -1 | awk \'{print $5}\'',

            # 操作系统信息
            'os_name': 'cat /etc/os-release | grep "^NAME=" | cut -d= -f2 | tr -d \'"\'',
            'os_version': 'cat /etc/os-release | grep "^VERSION=" | cut -d= -f2 | tr -d \'"\'',
            'os_id': 'cat /etc/os-release | grep "^ID=" | cut -d= -f2 | tr -d \'"\'',
            'kernel_version': 'uname -r',

            # 网络信息 - 获取所有网卡信息
            'network_interfaces': 'ip addr show | grep -E "^[0-9]+:" | awk -F: \'{print $2}\' | tr -d " "',
            'private_ip_eth0': 'ip addr show eth0 2>/dev/null | grep "inet " | awk \'{print $2}\' | cut -d/ -f1 | head -1',
            'private_ip_eth1': 'ip addr show eth1 2>/dev/null | grep "inet " | awk \'{print $2}\' | cut -d/ -f1 | head -1',
            'private_ip_ens33': 'ip addr show ens33 2>/dev/null | grep "inet " | awk \'{print $2}\' | cut -d/ -f1 | head -1',
            'private_ip_ens34': 'ip addr show ens34 2>/dev/null | grep "inet " | awk \'{print $2}\' | cut -d/ -f1 | head -1',
            'private_ip_ens160': 'ip addr show ens160 2>/dev/null | grep "inet " | awk \'{print $2}\' | cut -d/ -f1 | head -1',
            'private_ip_enp0s3': 'ip addr show enp0s3 2>/dev/null | grep "inet " | awk \'{print $2}\' | cut -d/ -f1 | head -1',
            'private_ip_enp0s8': 'ip addr show enp0s8 2>/dev/null | grep "inet " | awk \'{print $2}\' | cut -d/ -f1 | head -1',
            'all_private_ips': 'ip addr show | grep "inet " | grep -v "127.0.0.1" | awk \'{print $2}\' | cut -d/ -f1',
            'hostname_sys': 'hostname',
            'hostname_fqdn': 'hostname -f',

            # 系统负载和运行时间
            'uptime': 'uptime',
            'load_average': 'cat /proc/loadavg | awk \'{print $1, $2, $3}\'',

            # 系统环境判断
            'is_docker': 'if [ -f /.dockerenv ]; then echo "Docker"; elif [ -f /proc/1/cgroup ] && grep -q docker /proc/1/cgroup; then echo "Docker"; else echo "Physical"; fi',
            'is_vm': 'if command -v dmidecode >/dev/null 2>&1; then dmidecode -s system-product-name 2>/dev/null | grep -i "virtual\\|vmware\\|kvm\\|qemu\\|xen" && echo "Virtual" || echo "Physical"; else echo "Unknown"; fi'
        }

        # 执行所有命令
        for key, command in commands.items():
            try:
                _, stdout, _ = ssh.exec_command(command, timeout=10)
                output = stdout.read().decode().strip()
                if output:
                    system_info[key] = output
            except Exception as e:
                logger.debug(f"执行命令 {command} 失败: {e}")

        ssh.close()

        # 处理和格式化信息
        processed_info = process_system_info(system_info)
        return processed_info

    except Exception as e:
        logger.error(f"获取主机 {host.hostname} 增强系统信息失败: {e}")
        return {}


def is_private_ip(ip):
    """判断是否为内网IP"""
    try:
        import ipaddress
        ip_obj = ipaddress.ip_address(ip)
        return ip_obj.is_private
    except:
        # 简单判断
        return (ip.startswith('10.') or
                ip.startswith('172.') or
                ip.startswith('192.168.'))


def process_system_info(raw_info):
    """处理和格式化系统信息"""
    processed = {}

    # 处理CPU信息
    if 'cpu_model' in raw_info:
        processed['cpu_info'] = raw_info['cpu_model']

    if 'cpu_cores' in raw_info:
        try:
            cores = int(raw_info['cpu_cores'])
            processed['cpu'] = f"{cores}核"  # 格式化为 "4核" 这样的格式
        except:
            processed['cpu'] = raw_info['cpu_cores']

    if 'cpu_arch' in raw_info:
        processed['cpu_arch'] = raw_info['cpu_arch']

    # 处理内存信息
    if 'memory_total' in raw_info:
        # memory字段只保存总内存大小
        processed['memory'] = raw_info['memory_total']

        # memory_info字段保存详细信息
        memory_parts = []
        if raw_info.get('memory_total'):
            memory_parts.append(f"总计: {raw_info['memory_total']}")
        if raw_info.get('memory_used'):
            memory_parts.append(f"已用: {raw_info['memory_used']}")
        if raw_info.get('memory_available'):
            memory_parts.append(f"可用: {raw_info['memory_available']}")

        if memory_parts:
            processed['memory_info'] = ", ".join(memory_parts)

    # 处理磁盘信息
    if 'disk_total' in raw_info:
        # disk字段只保存总磁盘大小
        processed['disk'] = raw_info['disk_total']

        # disk_info字段保存详细信息
        disk_parts = []
        if raw_info.get('disk_total'):
            disk_parts.append(f"总计: {raw_info['disk_total']}")
        if raw_info.get('disk_used'):
            disk_parts.append(f"已用: {raw_info['disk_used']}")
        if raw_info.get('disk_available'):
            disk_parts.append(f"可用: {raw_info['disk_available']}")
        if raw_info.get('disk_usage'):
            disk_parts.append(f"使用率: {raw_info['disk_usage']}")

        if disk_parts:
            processed['disk_info'] = ", ".join(disk_parts)

    # 处理操作系统信息
    if 'os_name' in raw_info:
        os_name = raw_info['os_name']
        os_version = raw_info.get('os_version', '')
        processed['os'] = f"{os_name} {os_version}".strip()

        # 系统类型
        if 'os_id' in raw_info:
            processed['system_type'] = raw_info['os_id']

        # 系统版本
        if os_version:
            processed['os_version'] = os_version

    # 处理网络信息 - 智能获取内网IP，优先172网段
    private_ip = None

    # 收集所有可能的内网IP
    all_candidate_ips = []

    # 从各种网卡获取IP
    network_fields = [
        'private_ip_eth0', 'private_ip_eth1',
        'private_ip_ens33', 'private_ip_ens34', 'private_ip_ens160',
        'private_ip_enp0s3', 'private_ip_enp0s8'
    ]

    for field in network_fields:
        if field in raw_info and raw_info[field]:
            ip = raw_info[field].strip()
            if ip and is_private_ip(ip):
                all_candidate_ips.append(ip)

    # 从所有IP中收集内网IP
    if 'all_private_ips' in raw_info:
        all_ips = raw_info['all_private_ips'].strip().split('\n')
        for ip in all_ips:
            ip = ip.strip()
            if ip and is_private_ip(ip) and ip not in all_candidate_ips:
                all_candidate_ips.append(ip)

    # 按优先级选择IP：172网段 > 10网段 > 192.168网段
    if all_candidate_ips:
        # 优先选择172网段
        for ip in all_candidate_ips:
            if ip.startswith('172.'):
                private_ip = ip
                break

        # 如果没有172网段，选择10网段
        if not private_ip:
            for ip in all_candidate_ips:
                if ip.startswith('10.'):
                    private_ip = ip
                    break

        # 最后选择192.168网段
        if not private_ip:
            for ip in all_candidate_ips:
                if ip.startswith('192.168.'):
                    private_ip = ip
                    break

        # 如果还没有，选择第一个
        if not private_ip and all_candidate_ips:
            private_ip = all_candidate_ips[0]

    # 设置内网IP，如果获取不到则显示"-"
    if private_ip:
        processed['private_ip'] = private_ip
    else:
        processed['private_ip'] = '-'

    # 处理主机名（如果当前主机名为空或默认值）
    if 'hostname_sys' in raw_info:
        hostname = raw_info['hostname_sys']
        # 如果获取到了有效的主机名，则使用它
        if hostname and hostname not in ['localhost', 'localhost.localdomain']:
            processed['hostname'] = hostname
        elif 'hostname_fqdn' in raw_info and raw_info['hostname_fqdn']:
            # 尝试使用FQDN
            processed['hostname'] = raw_info['hostname_fqdn']

    # 处理系统环境
    environment_info = []
    if 'is_docker' in raw_info and 'Docker' in raw_info['is_docker']:
        environment_info.append('Docker')
    if 'is_vm' in raw_info and 'Virtual' in raw_info['is_vm']:
        environment_info.append('Virtual Machine')

    if environment_info:
        processed['system_environment'] = ', '.join(environment_info)
    else:
        processed['system_environment'] = 'Physical Server'

    return processed


def auto_detect_enhanced_host_info(host_id):
    """自动检测增强的主机信息"""
    try:
        host = Host.objects.get(id=host_id)
        logger.info(f"开始检测主机 {host.hostname} 的详细信息")

        system_info = get_enhanced_system_info(host)

        if system_info:
            # 更新主机信息
            updated_fields = []
            for key, value in system_info.items():
                if hasattr(host, key) and value:
                    old_value = getattr(host, key)
                    if old_value != value:
                        setattr(host, key, value)
                        updated_fields.append(key)
                        # logger.info(f"更新字段 {key}: {old_value} -> {value}")  # 注释掉避免终端输出干扰

            if updated_fields:
                host.updated_at = timezone.now()
                host.save()
                # logger.info(f"主机 {host.hostname} 信息更新完成，更新了 {len(updated_fields)} 个字段")  # 注释掉避免终端输出干扰

            return {
                'success': True,
                'message': f'主机信息检测完成，更新了 {len(updated_fields)} 个字段',
                'data': system_info,
                'updated_fields': updated_fields
            }
        else:
            return {
                'success': False,
                'message': '无法获取主机信息，请检查连接配置'
            }

    except Host.DoesNotExist:
        return {
            'success': False,
            'message': '主机不存在'
        }
    except Exception as e:
        logger.error(f"自动检测主机信息失败: {e}")
        return {
            'success': False,
            'message': f'检测失败: {str(e)}'
        }
